package com.security.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户
 *
 * @author 顾志杰
 * @date 2020/7/16-9:58
 */
@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SysUser implements UserDetails {
    private static final long serialVersionUID = -5486278850149693774L;
    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    private String id;

    private String userName;

    private String passWord;

    @ManyToMany(fetch = FetchType.EAGER)
    private List<SysRole> roles;

    /**
     * 返回角色列表
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<String> collect = roles.stream().map(r->"ROLE_"+r.getRoleCode()).collect(Collectors.toList());
        roles.forEach(m-> collect.addAll(m.getMenus().stream().map(url->url.getUrl()+"/**").collect(Collectors.toList())));
        return AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", collect));
    }

    @Override
    public String getPassword() {
        return this.passWord;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }


}
